var EquipmentForm = function () {
  var template = /* html */ `
    <div class="equipment-form" v-loading.fullscreen.lock="loading">
      <el-form label-width="calc(5em + 12px)" :model="equipmentForm" size="medium">
        <el-form-item required label="设备编号">
          <template v-if="type === 'add'">
            <el-input class="form-input" v-model="equipmentForm.equipmentNo" placeholder="请输入设备编号" :disabled="checkuniqueNoLoading"
              :suffix-icon="checkuniqueNoLoading?'el-icon-loading':undefined" @change="checkUniqueNo">
            </el-input>
            <div class="el-form-item__error">
              <el-collapse-transition>
                <div v-if="!hasUniqueNo">设备编号已存在</div>
              </el-collapse-transition>
            </div>
          </template>
          <template v-else>
            <span>{{equipmentForm.equipmentNo}}</span>
          </template>
        </el-form-item>
        <el-form-item required label="设备名称">
          <el-input class="form-input" v-model="equipmentForm.equipmentName" placeholder="请输入设备名称">
          </el-input>
        </el-form-item>
        <el-form-item required label="设备图片">
          <img-upload ref="equipmentUpload" v-model="equipmentForm.equipmentImage" errorMsg="请上传图片格式文件" :auto-upload="false"
            :upload-check-method="checkImgValid" @upload-success="toSaveEquipment">
          </img-upload>
        </el-form-item>
        <el-form-item label="设备类型">
          <el-input class="form-input" v-model="equipmentForm.deviceType" placeholder="请输入设备类型"></el-input>
        </el-form-item>
        <el-form-item label="上位机">
          <el-input class="form-input" v-model="equipmentForm.upperComputer" placeholder="请输入上位机"></el-input>
        </el-form-item>
        <el-form-item label="生产厂家">
          <el-input class="form-input" v-model="equipmentForm.manufacturer" placeholder="请输入生产厂家">
          </el-input>
        </el-form-item>
        <el-form-item label="部门-车间">
          <el-cascader clearable filterable class="form-input" v-model="equipmentForm.depWork" :options="deptWorkshopList" :props="{children:'workshops'}"
            separator="-"></el-cascader>
        </el-form-item>
        <el-form-item label="采购单价">
          <el-input-number is-decimal-zero class="form-input" v-model="equipmentForm.purchasePrice" controls-position="right" :min="0" :precision="2"
            placeholder="请输入采购单价">
          </el-input-number>
        </el-form-item>
        <el-form-item label="采购日期">
          <el-date-picker class="form-input" v-model="equipmentForm.purchaseTime" format="yyyy-MM-dd" value-format="timestamp" :editable="false"
            placeholder="请选择采购日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="折旧年限">
          <el-date-picker class="form-input" v-model="equipmentForm.depreciableLife" format="yyyy-MM-dd" value-format="timestamp" :editable="false"
            placeholder="请选择折旧年限">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="工作时间">
          <el-button size="small" type="primary" @click="setWorkTime">设置</el-button>
          <div class="work-time-content">
            <div v-for="(workTime,index) in equipmentForm.workTimeList" :key="'workTime_'+index">
              <span style="margin-right:5px">第{{index+1}}时间段</span>
              <span>{{moment(workTime.startTime).format('HH:mm')}} - {{moment(workTime.endTime).format('HH:mm')}}</span>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="日工作时长">
          <time-duration-input v-model="equipmentForm.dailyWorkingHours"></time-duration-input>
        </el-form-item>
        <el-form-item label="使用电表">
          <el-select clearable filterable class="form-input" v-model="equipmentForm.energyId" placeholder="请选择使用的电表">
            <template v-for="eleEnergy in eleEnergyList">
              <el-option v-if="eleEnergy.state===2||eleEnergy.id===equipmentForm.energyId" :key="eleEnergy.id" :value="eleEnergy.id" :label="eleEnergy.no">
              </el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="超时断电时间设定(s)" class="more-text-form-item">
          <el-input-number class="form-input" v-model="equipmentForm.timeoutBreakElectricityTime" :min="1" :precision="0" controls-position="right"
            placeholder="请输入超时断电时间"></el-input-number>
        </el-form-item>
        <el-form-item label="使用气表">
          <el-select clearable filterable class="form-input" v-model="equipmentForm.flowId" placeholder="请选择使用的气表">
            <template v-for="gasEnergy in gasEnergyList">
              <el-option v-if="gasEnergy.state===2||gasEnergy.id===equipmentForm.flowId" :key="gasEnergy.id" :value="gasEnergy.id" :label="gasEnergy.no">
              </el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="超时断气时间设定(s)" class="more-text-form-item">
          <el-input-number class="form-input" v-model="equipmentForm.timeoutBreakFlowTime" :min="1" :precision="0" controls-position="right"
            placeholder="请输入超时断气时间"></el-input-number>
        </el-form-item>
        <el-form-item label="加工对象">
          <el-select clearable filterable class="form-input" v-model="equipmentForm.machining" placeholder="请选择加工对象">
            <template v-for="machining in machiningList">
              <el-option :key="machining" :value="machining">
              </el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="加工工序">
          <el-button size="small" type="primary" @click="setWorkProcedure">设置</el-button>
          <div style="line-height:20px">
            <div v-for="(procedure,index) in equipmentForm.procedureList" :key="'procedure'+index">
              <span>工序:{{getProcessName(procedure.processId)}}</span>
              <span style="margin-left:10px">最大加工时间:{{procedure.maxProcessTime}}秒</span>
            </div>
          </div>
        </el-form-item>
        <el-form-item required label="产能比例">
          <el-input-number style="width:80px" v-model="equipmentForm.startProportion" :min="1" :precision="0" :controls="false"></el-input-number>
          <span>:</span>
          <el-input-number style="width:80px" v-model="equipmentForm.endProportion" :min="1" :precision="0" :controls="false"></el-input-number>
        </el-form-item>
        <el-form-item label="设备状态">
          <el-switch v-model="equipmentForm.mainSwitch" active-text="开机" inactive-text="关机" active-value="true" inactive-value="false"
            inactive-color="#F56C6C"></el-switch>
        </el-form-item>
        <el-form-item label="手动操作">
          <el-switch v-model="equipmentForm.isHandOperation" active-text="打开" inactive-text="关闭" :active-value="1" :inactive-value="0"
            inactive-color="#F56C6C"></el-switch>
        </el-form-item>
        <el-form-item label="看板展示">
          <el-switch v-model="equipmentForm.showInBoard" active-text="展示" inactive-text="不展示" :active-value="1" :inactive-value="0"
            inactive-color="#F56C6C"></el-switch>
        </el-form-item>
        <el-form-item label="微信提醒">
          <el-switch v-model="equipmentForm.sendMessage" active-text="提醒" inactive-text="不提醒" :active-value="1" :inactive-value="0"
            inactive-color="#F56C6C"></el-switch>
        </el-form-item>
      </el-form>

      <div style="height:30px;font-size:18px">物联网卡绑定</div>
      <el-form class="card-info" size="medium" label-width="auto">
        <el-form-item label="物联网卡ID">
          <el-input class="form-input" v-model="equipmentForm.internetThingsCard" placeholder="请输入设备需要绑定的物联网卡" >
          </el-input>
        </el-form-item>
      </el-form>

      <div style="text-align:center">
        <el-button type="primary" size="medium" :loading="hasSubmit" @click="save">
          <span v-if="type === 'add'">确定</span>
          <span v-else>修改</span>
        </el-button>
      </div>

      <el-dialog append-to-body :title="dialogTitle" :visible.sync="openDialog" width="400px" top="15vh" :close-on-click-modal="false"
        :close-on-press-escape="false" @closed="dialogClosed">
        <div style="height:calc(70vh - 54px);overflow:auto">
          <component v-if="openDialog" :is="compName" :equipment="equipmentForm" :dropdown-option="dropdownOption" @close="openDialog=false"></component>
        </div>
      </el-dialog>
    </div>
  `;

  return {
    props: {
      equipment: {
        type: Object,
        default: function () {
          return null;
        }
      },
      type: {
        type: String,
        required: true
      },
      dropdownOption: {
        type: Object,
        required: true
      }
    },

    data: function () {
      var equipmentForm = this.getInitData();
      return {
        loading: false,
        equipmentForm: equipmentForm,
        eleEnergyList: [],
        gasEnergyList: [],
        machiningList: [],
        deptWorkshopList: [],
        processList: [],
        itCardList: [],
        hasUniqueNo: true,
        checkuniqueNoLoading: false,
        hasSubmit: false,
        openDialog: false,
        dialogTitle: '',
        compName: null,
        moment: moment
      };
    },

    watch: {
      checkuniqueNoLoading: function (loading) {
        if (loading) {
          return;
        }

        if (this.hasSubmit) {
          this.save();
        }
      }
    },

    created: function () {
      this.loading = true;
      var self = this;
      Promise.all([
        this.setEleEnergyList(),
        this.setGasEnergyList(),
        this.setMachiningList(),
        this.setDeptWorkshopList(),
        this.setProcessList()
      ]).then(function () {
        self.loading = false;
      }).catch(function () {
        self.loading = false;
      });
    },

    methods: {
      getInitData: function () {
        var equipment = this.equipment;
        equipment = new EquipmentFormModel(equipment);
        return equipment;
      },

      setEleEnergyList: function () {
        var dropdownOption = this.dropdownOption;
        var eleEnergyList = dropdownOption.eleEnergyList;
        if (eleEnergyList !== undefined) {
          this.eleEnergyList = eleEnergyList;
          return Promise.resolve(eleEnergyList);
        }

        var self = this;
        return ajaxRequest('energy/getAllElectricEnergy').then(function (eleEnergyList) {
          dropdownOption.eleEnergyList = eleEnergyList;
          self.eleEnergyList = eleEnergyList;
          return eleEnergyList;
        });
      },

      setGasEnergyList: function () {
        var dropdownOption = this.dropdownOption;
        var gasEnergyList = dropdownOption.gasEnergyList;
        if (gasEnergyList !== undefined) {
          this.gasEnergyList = gasEnergyList;
          return Promise.resolve(gasEnergyList);
        }

        var self = this;
        return ajaxRequest('energy/getAllFlowEnergy').then(function (gasEnergyList) {
          dropdownOption.gasEnergyList = gasEnergyList;
          self.gasEnergyList = gasEnergyList;
          return gasEnergyList;
        });
      },

      setMachiningList: function () {
        var dropdownOption = this.dropdownOption;
        var machiningList = dropdownOption.machiningList;
        if (machiningList !== undefined) {
          this.machiningList = machiningList;
          return Promise.resolve(machiningList);
        }

        var self = this;
        return ajaxRequest('basicData/getRowMaterialType').then(function (machiningList) {
          dropdownOption.machiningList = machiningList;
          self.machiningList = machiningList;
          return machiningList;
        });
      },

      setDeptWorkshopList: function () {
        var dropdownOption = this.dropdownOption;
        var deptWorkshopList = dropdownOption.deptWorkshopList;
        if (deptWorkshopList !== undefined) {
          this.deptWorkshopList = deptWorkshopList;
          return Promise.resolve(deptWorkshopList);
        }

        var self = this;
        return ModuleUtil.getDepAndWorkShop().then(function (deptWorkshopList) {
          dropdownOption.deptWorkshopList = deptWorkshopList;
          self.deptWorkshopList = deptWorkshopList;
          return deptWorkshopList;
        });
      },

      setProcessList: function () {
        var dropdownOption = this.dropdownOption;
        var processList = dropdownOption.processList;
        if (processList !== undefined) {
          this.processList = processList;
          return Promise.resolve(processList);
        }

        var self = this;
        return ajaxRequest('procedure/getAllProcess').then(function (processList) {
          processList = _.uniqBy(processList, 'processName');
          processList = _.map(processList, function (processObj) {
            return {
              id: processObj.id,
              name: processObj.processName
            }
          });
          dropdownOption.processList = processList;
          self.processList = processList;
          return processList;
        });
      },

      getFormatCard: function (itCard) {
        return {
          id: itCard.id,
          internetThingsCard: itCard.internetThingsCard,
          terminalUser: itCard.terminalUser
        };
      },

      checkUniqueNo: function () {
        var equipmentNo = this.equipmentForm.equipmentNo;
        if (equipmentNo === '') {
          this.hasUniqueNo = true;
          return;
        }

        this.checkuniqueNoLoading = true;
        var self = this;
        ajaxRequest('equipment/checkEquipmentNoUnique', {
          equipmentNo: equipmentNo
        }).then(function (equipmentNoUnique) {
          self.hasUniqueNo = equipmentNoUnique;
          self.checkuniqueNoLoading = false;
        }).catch(function () {
          self.checkuniqueNoLoading = false;
        })
      },

      setWorkTime: function () {
        this.dialogTitle = '工作时间设置';
        this.compName = 'work-time-setting';
        this.openDialog = true;
      },

      setWorkProcedure: function () {
        this.dialogTitle = '加工工序设置';
        this.compName = 'work-procedure-setting';
        this.openDialog = true;
      },

      dialogClosed: function () {
        this.dialogTitle = '';
        this.compName = null;
      },

      save: function () {
        if (this.type === 'add') {
          if (this.checkuniqueNoLoading) {
            this.hasSubmit = true;
            return;
          }
          this.hasSubmit = false;
        }
        if (!this.checkValid()) {
          return;
        }
        this.$refs.equipmentUpload.submit();
      },

      checkValid: function () {
        var equipmentForm = this.equipmentForm;
        var fields = ['equipmentNo', 'equipmentName', 'startProportion', 'endProportion'];
        var code = CheckVaildUtil.checkNullField(fields, equipmentForm);
        if (code !== '') {
          var msg = i18n.getMsg(`equipmentInfo.error.${code}`);
          this.$alert(msg, '信息');
          return false;
        }

        var imgExist = this.$refs.equipmentUpload.checkImgExist();
        if (!imgExist) {
          this.$alert(i18n.getMsg('equipmentInfo.error.equipmentImage'), '信息');
          return false;
        }

        if (this.type === 'add' && !this.hasUniqueNo) {
          this.$alert(i18n.getMsg('equipmentInfo.error.notUniqueNo'), '信息');
          return false;
        }

        return true;
      },

      toSaveEquipment: function () {
        var equipmentForm = this.equipmentForm;
        var postData = equipmentForm.getObject();
        var type = this.type;
        if (type === 'add') {
          this.addEquipment(postData);
        } else {
          this.updateEquipment(postData);
        }
      },

      addEquipment: function (postData) {
        this.loading = true;
        var self = this;
        ajaxRequest('equipment/addEquipment', postData).then(function () {
          self.$alert('添加设备成功', '信息', {
            callback: function () {
              self.$emit('save-success');
            }
          });
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      updateEquipment: function (postData) {
        this.loading = true;
        var self = this;
        ajaxRequest('equipment/updateEquipment', postData).then(function () {
          self.$alert('修改设备成功', '信息', {
            callback: function () {
              self.$emit('save-success');
            }
          });
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      getProcessName: function (id) {
        var processList = this.processList;
        var processObj = _.find(processList, {
          id: id
        });
        if (processObj === undefined) {
          return '';
        }
        return processObj.name;
      },

      checkImgValid: function (file) {
        var type = file.type;
        if (type.indexOf('image/') !== 0) {
          this.$message.error({
            message: '请选择图片格式文件上传',
            duration: 2000
          });
          return Promise.resolve(false);
        }

        return Promise.resolve(true);
      }
    },

    components: {
      TimeDurationInput: TimeDurationInput,
      ImgUpload: ImgUpload,
      WorkTimeSetting: WorkTimeSetting,
      workProcedureSetting: workProcedureSetting
    },

    template: template
  };
}();
